# Build script for the single-purpose initramfs (Live CD).
#
# Copyright (c) 2017-2020, 2022 Matias Fonzo, <selk@dragora.org>.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

mkdir -p -- "${rootdir}/initrd"
cd -- "${rootdir}/initrd"

# Create essential directories for the image

mkdir -p proc sys dev UP
chmod 755 proc sys dev UP

cat << "EOF" > init
#! /bin/busybox hush

set -x

/bin/busybox mount -n -o nosuid,noexec,nodev -t proc proc /proc
/bin/busybox mount -n -o nosuid,noexec,nodev -t sysfs sysfs /sys
/bin/busybox mount -n -t devtmpfs devtmpfs /dev
/bin/busybox sleep 5

# Mount tmpfs plus create directories
/bin/busybox mount -n -w -o size=100% -t tmpfs tmpfs /UP
/bin/busybox mkdir -p \
 /UP/cdrom /UP/squash /UP/rw /UP/workdir /UP/union

# Mount ISO and system image
/bin/busybox mount -n -r -t iso9660 LABEL="Dragora_@ARCH@" /UP/cdrom

# Be the system or be dead!
/bin/busybox mount -n -r -o loop -t squashfs \
 /UP/cdrom/dragora.sfs /UP/squash || /bin/busybox sleep 3323;

# Merge Squashfs with OverlayFS
/bin/busybox mount -n \
 -o lowerdir=/UP/squash,upperdir=/UP/rw,workdir=/UP/workdir \
 -t overlay overlay /UP/union

# Move virtual file systems prior to switch_root
/bin/busybox mount -n --move /dev   /UP/union/dev
/bin/busybox mount -n --move /proc  /UP/union/proc
/bin/busybox mount -n --move /sys   /UP/union/sys

: > /UP/union/fastboot
exec /bin/busybox switch_root /UP/union /sbin/init

EOF

sed -i "s/@ARCH@/${package_arch}/" init
chmod 750 init

# Make initramfs

rm -f ./initrd.img
find . | sed -e 's!^./!!' | cpio -oC512 -H newc | \
 lzip -s16 -0c > initrd.img

